<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\services\user;

use app\kefuapi\controller\Product;
use app\model\product\Brand;
use app\model\product\product\StoreProduct;
use app\model\product\sku\StoreProductAttr;
use app\model\user\UserSearch;
use app\services\BaseServices;
use app\dao\user\UserSearchDao;
use app\services\product\product\StoreProductServices;
use Lizhichao\Word\VicWord;
use think\cache\driver\Redis;
use think\Db;
use think\Log;

/**
 *
 * Class UserLabelServices
 * @package app\services\user
 *  * @method getColumn(array $where, string $field, string $key = '') 获取某个字段数组
 *  * @method getKeywordResult(int $uid, string $keyword, int $preTime = 7200) 获取全局|用户某个关键词搜素结果
 */
class UserSearchServices extends BaseServices
{
    const USER_SEARCH_PRIFIX = 'history_';
    const USER_SEARCH_DB = 1;

    /**
     * UserSearchServices constructor.
     * @param UserSearchDao $dao
     */
    public function __construct(UserSearchDao $dao)
    {
        $this->dao = $dao;
    }


    /**
     * 获取用户搜索关键词列表
     * @param int $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserList(int $uid)
    {
        if (!$uid) {
            return [];
        }
        [$page, $limit] = $this->getPageValue();
        return $this->dao->getList(['uid' => $uid, 'is_del' => 0], 'add_time desc,num desc', $page, $limit);
    }

    /**
     * 用户增加搜索记录
     * @param int $uid
     * @param string $key
     * @param array $result
     */
    public function saveUserSearch(int $uid, string $keyword, array $vicword, array $result)
    {
        $result = json_encode($result);
        $vicword = json_encode($vicword, JSON_UNESCAPED_UNICODE);
        $userkeyword = $this->dao->getKeywordResult($uid, $keyword, 0);
        $data = [];
        $data['result'] = $result;
        $data['vicword'] = $vicword;
        $data['add_time'] = time();
        if ($userkeyword) {
            $data['num'] = $userkeyword['num'] + 1;
            $this->dao->update(['id' => $userkeyword['id']], $data);
        } else {
            $data['uid'] = $uid;
            $data['keyword'] = $keyword;
            $this->dao->save($data);
        }
        return true;
    }

    /**
     * Note: 搜索历史数据，redis存储
     * DateTime: 2023/10/21 17:45
     * @param $searchWord
     * @param $uid
     * @return \think\Response
     */
    public function saveUserSearchByRedis(int $uid, string $keyword)
    {
        $cacheKey = self::USER_SEARCH_PRIFIX . $uid;
        $redis = $this->getRedisServer();

        // 读取的长度
        $len = $redis->llen($cacheKey);
        if ($len >= 5) {
            $redis->rPop($cacheKey);// 移除右侧
            $redis->lPush($cacheKey, $keyword); // 左侧加入
        } else {
            $redis->lPush($cacheKey, $keyword);
        }

        return true;
    }

    /**
     * Note: 获取搜索历史数据
     * DateTime: 2023/10/21 18:16
     * @param int $uid
     * @return mixed
     */
    public function getUserSearchHistory(int $uid)
    {

        return UserSearch::where('uid', $uid)->where('is_del', 0)->field('id,keyword')->order('upd_time desc')->order('id desc')->limit(10)->select()->toArray();

//        $cacheKey = self::USER_SEARCH_PRIFIX . $uid;
//        $redis = $this->getRedisServer();
//        $res = $redis->handler()->lrange($cacheKey, 0, -1);
//        return $res;
    }

    /**
     * Note: 删除历史搜索数据
     * DateTime: 2023/10/21 18:16
     * @param int $uid
     * @return mixed
     */
    public function delUserSearchHistory(int $uid)
    {
        $cacheKey = self::USER_SEARCH_PRIFIX . $uid;
        $redis = $this->getRedisServer();
        $res = $redis->del($cacheKey);
        UserSearch::where('uid', $uid)->update(['uid' => $uid, 'is_del' => 1]);
        return $res;
    }


    public function getHotSearchHistory()
    {
        return UserSearch::where('is_del', 0)->order('num', 'desc')->limit(8)->column('id, keyword');
    }


    public function getSearchList($keyword, $sort_type, $sort_value, $need_record = false, $uid = 0, $brand_id = 0)
    {

        $brandInfo = [];

        $query = StoreProduct::with(['defaultSku', 'label'])->where('is_del', 0)->where('is_show', 1)->where('publish_time', '<=', time());
        if ($keyword) {
            // 获取 attr 关联表中 对应符合的id 集合组
//            $query->where('store_name', 'like', '%'. $keyword . '%');
            $product_ids = StoreProductAttr::where('attr_values', 'like', '%' . $keyword . '%')->where('type', 0)->column('product_id');
            $query = $query->where(function ($query) use ($product_ids, $keyword) {
                $query->whereIn('id', $product_ids)->whereOr('store_name', 'like', '%' . $keyword . '%');
            });

            // 搜索有没有对应品牌
            $brandInfo = Brand::where('status', 1)->where('is_del', 0)->where('name', 'like', '%'. $keyword . '%')->column('id, logo, name');
            $brandInfo = ($brandInfo) ? $brandInfo[0] : null;

        }

        if ($brand_id) {
            $query->where('brand_id', $brand_id);
        }

        // 确保 sort_type 和 sort_value 是有效的，并设置排序
        $sortDirection = $sort_value == 1 ? 'asc' : 'desc';
        switch ($sort_type) {
            case 0:
                $query = $query->order('id', 'desc');
                break;
            case 1:
                $query = $query->order('price', $sortDirection);
                break;
            case 2:
                $query = $query->order('sales', $sortDirection);
                break;
            // 可以添加更多的 case 来处理其他排序类型
            default:
                // 默认排序或不进行排序
                break;
        }

        $products = $query->paginate();

        if ($need_record && $keyword) {
            $userSearch = UserSearch::where('uid', $uid)->where('keyword', $keyword)->where('is_del', 0)->find();
            if ($userSearch) {
                $userSearch->num = $userSearch->num + 1;
                $userSearch->upd_time = time();
                $userSearch->save();
            } else {
                UserSearch::create([
                    'uid'   =>  $uid,
                    'keyword'   =>  $keyword,
                    'vicword'   =>  [],
                    'num'   =>  1,
                    'add_time'  =>  time()
                ]);
            }
        }

        $storeProductService = app()->make(StoreProductServices::class);

        return [
            'brandInfo' =>  $brandInfo,
            'list'  =>  $storeProductService->filterList($products->items()),
            'count' =>  $products->total()
        ];
    }

    public function getSearchFilterData()
    {
        return [
            'brandInfo' =>  Brand::where('status', 1)->where('is_del', 0)->column('id, logo, name')
        ];
    }

    public function getSearchRecommend()
    {
        $storeProductService = app()->make(StoreProductServices::class);

        $ids = StoreProduct::where('is_del', 0)->where('is_show', 1)
            ->orderRand()->limit(6)->column('id');

        $products = StoreProduct::with(['defaultSku', 'label'])->whereIn('id', $ids)->select();
        $list = $storeProductService->filterList($products);
        shuffle($list);
        return $list;
    }

    public function getRedisServer()
    {
        return new Redis(array_merge(config('cache.stores.redis'), ['select' => self::USER_SEARCH_DB]));
    }
}
